package chat.server;

import chat.logic.ClientAction;
import java.io.*;
import java.net.*;
import java.text.DateFormat;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * @time Oct 28, 2009, 12:55:14 PM
 * @author fdcube
 * @version FreeChat-Server v1.1.2
 */
public class Connection extends Thread {

    private Socket Client;
    private int Counter;
    BufferedReader in = null;

    public Connection(Socket Client, int Counter) {
        this.Client = Client;
        this.Counter = Counter;
    }

    private void doGetSend(PrintStream out, String GetData) throws IOException {
        File file;
        if (GetData.equals("")) {
            file = new File("index.lf");
        } else {
            file = new File(GetData);
        }
        if (file.exists() && !file.isDirectory()) {
            out.println("HTTP/1.1 200 OK");
            out.println("Server: FreeChatServer/1.1.2");
            if (GetData.endsWith("png")) {
                out.println("Content-Type: image/png; charset=utf-8");
            } else if (GetData.endsWith("gif")) {
                out.println("Content-Type: image/gif; charset=utf-8");
            } else if (GetData.endsWith("css")) {
                out.println("Content-Type: text/css; charset=utf-8");
            } else {
                out.println("Content-Type: text/html; charset=utf-8");
            }
            int len = (int) file.length();
            out.println("Content_Length:" + len);
            out.println("Date: " + DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT, Locale.US).format(new Date()));
            out.println();
            DataInputStream inFile = new DataInputStream(new FileInputStream(file));
            byte buf[] = new byte[len];
            inFile.readFully(buf);
            out.write(buf, 0, len);
            out.flush();
            inFile.close();
        }
    }

    private void doPostSend(PrintWriter out, String OutData) throws UnsupportedEncodingException {
        System.out.println("Send: " + OutData + " Length: " + OutData.length());
        OutData = URLEncoder.encode(OutData, "UTF-8");
        out.println("HTTP/1.1 200 OK");
        out.println("Server: FreeChatServer/1.1.2");
        out.println("Content-Type: text/html; charset=utf-8");
        out.println("Content-Length: " + OutData.length());
        out.println("Date: " + DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT, Locale.US).format(new Date()));
        out.println();
        out.println(OutData);
        out.close();
    }

    private void doPost(Socket Client, BufferedReader in) throws IOException {
        String line = "";
        int contentLength = 0;
        while ((line = in.readLine()) != null) {
            if (line.startsWith("Content-Length")) {
                contentLength = Integer.parseInt(line.substring(line.indexOf(':') + 1).trim());
            }
            if (line.equals("")) {
                break;
            }
        }
        char[] tmp = new char[contentLength];
        for (int i = 0; i < contentLength; i++) {
            tmp[i] = (char) in.read();
        }
        String PostData = URLDecoder.decode(String.valueOf(tmp), "UTF-8");
        System.out.println("POST Resource:" + PostData);
        String OutData = ClientAction.Act(PostData);
        PrintWriter out = new PrintWriter(Client.getOutputStream(), true);
        doPostSend(out, OutData);
    }

    private void doGet(Socket Client, String line) throws UnsupportedEncodingException, IOException {
        String GetData = line.substring(line.indexOf('/') + 1, line.lastIndexOf('/') - 5);
        GetData = URLDecoder.decode(GetData, "UTF-8");
        PrintStream out = new PrintStream(Client.getOutputStream(), true);
        System.out.println("GET Resource:" + GetData);
        doGetSend(out, GetData);
    }

    private void doClose(Socket Client, BufferedReader in) {
        try {
            Client.close();
            in.close();
            System.out.println("conn已关闭.");
        } catch (IOException ex) {
            Logger.getLogger(Connection.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    @Override
    public void run() {
        try {
            System.out.println("Conn" + Counter + " Client Port:" + Client.getPort() + " Client IP:" + Client.getInetAddress());
            Client.setSoTimeout(20 * 1000);
            in = new BufferedReader(new InputStreamReader(Client.getInputStream(), "utf8"));
            String line = in.readLine();
            String method = new StringTokenizer(line).nextElement().toString();
            if ("POST".equalsIgnoreCase(method)) {
                doPost(Client, in);
            } else if ("GET".equalsIgnoreCase(method)) {
                doGet(Client, line);
            }
        } catch (IOException ex) {
            Logger.getLogger(Connection.class.getName()).log(Level.SEVERE, "Error", ex);
        } finally {
            doClose(Client, in);
        }
    }
}
